#!/usr/bin/env python

import roslib,sys
roslib.load_manifest('picasa')
import rospy

from picasa.srv import *

import gdata.photos.service
import gdata.media

from PIL import Image

class Picasa:
    url = '/data/feed/api/user/default/albumid/%s'

    def __init__( self, email, password, album = 'default'):
        print "email address is " + email
        client = gdata.photos.service.PhotosService()
        client.email    = email
        client.password = password
        client.source   = 'harris-the-robotic-photographer'
        client.ProgrammaticLogin()
        self.client = client
        self.defaultAlbum = album

    def _getType(self, filename):
        return Image.open(filename).format

    def postPhoto(self, req): 
        filename = req.file
        album = req.album or defaultAlbum
        title = req.title or ''
        description = req.description or ''
        url = self.url % (album)
        self.client.InsertPhotoSimple(
            url,
            title,
            description,
            filename,
            content_type='image/' + self._getType(filename).lower()
        )
        return True

    def createAlbum(self, title, summary=''):
        return self.InsertAlbum(title, album)

def run(username, password):
    picasa = Picasa(username, password)
    def upload_image(filename):
        return picasa.postPhoto(filename)
    rospy.init_node('picasa_server')
    rospy.Service('upload_image', ImageUpload, upload_image)
    rospy.spin()

    

if __name__ == '__main__':
    username = rospy.get_param('/image_uploader/username','')
    password = rospy.get_param('/image_uploader/password','')
    print 'creds: %s, %s' % (username,password)
    if username != '' and password != '':
        run(username, password)
    else:
        print "Please provide a username and a password"
